import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';
import request from '@/utils/request';

import find from 'lodash/find';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import AddOrEditUser from './addOrEditUser';
import guawa from './../../images/guawa.png';
import guawa2 from './../../images/guawa21.png';

const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ outbound, loading, global }) => ({
  outbound,
  global,
  loading: loading.models.outbound,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      all_warehouses:[]
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      outbound: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        outbound: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'outbound/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'outbound/changeLoaded',
          });
          dispatch({
            type: 'outbound/changeTableY',
          });
        },
      });

    }
    const that = this;
    request(`/all_warehouses`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          all_warehouses: response.data.data,
        });
      }

    });
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'outbound/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'outbound/changeTableY',
    });
  };
  findChildFunc = (cb) => {
    this.file = cb;
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.react-grid-Canvas');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'outbound/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      outbound: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label="出库单ID">
          {getFieldDecorator('id', {
            initialValue: searchParams.id,
          })(<Input style={{ width: '150px' }} placeholder="请输入"/>)}
        </FormItem>
        <FormItem label="类型">
          {getFieldDecorator('type', {
            initialValue: searchParams.type,
          })(
            <Select style={{ width: '120px' }} allowClear >
              {
                [{id:'',name:'全部'},{id:'write',name:'库存录入'},{id:'purchase',name:'采购出库'}].map((item, index) => {
                  return <Option key={index} value={item.id}>{item.name}</Option>;
                })
              }
            </Select>,
          )}
        </FormItem>
        <FormItem label="状态">
          {getFieldDecorator('status', {
            initialValue: searchParams.status,
          })(
            <Select style={{ width: '120px' }} allowClear >
              {
                [{id:'',name:'全部'},{id:-1,name:'未出库'},{id:1,name:'已出库'}].map((item, index) => {
                  return <Option key={index} value={item.id}>{item.name}</Option>;
                })
              }
            </Select>,
          )}
        </FormItem>
        <FormItem>


          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>

          {
            find(this.permissions, { name: 'account_add_and_edit' }) &&
            <Button
              icon="plus"
              style={{ marginLeft: 8 }}
              type="primary"
              onClick={
                () => {
                  this.setState({
                    addModal: true,
                  });
                }
              }
            >
              新建出库单
            </Button>
          }
        </FormItem>

      </Form>
    );
  }

  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    let meterskey=[]
    for(let i in formValues){
      let splitKey=i.split('-')
      let len=splitKey.length;
      if(len>=2){
        if(meterskey.indexOf(splitKey[1])<0){
          meterskey.push(splitKey[1])
        }
      }
    }
    const metersArr=[]
    for(let i=0;i<meterskey.length;i++){
      if(formValues[`material_id-${meterskey[i]}`]){
        metersArr.push({
          material_id:formValues[`material_id-${meterskey[i]}`],
          warehouse_area_id:formValues[`warehouse_area_id-${meterskey[i]}`]?formValues[`warehouse_area_id-${meterskey[i]}`][formValues[`warehouse_area_id-${meterskey[i]}`].length-1]:'',
          count:formValues[`count-${meterskey[i]}`],
        })
      }

    }
    console.log('metersArr',metersArr)
    const that = this;
    this.props.dispatch({
      type: 'outbound/add',
      payload: {
        ...formValues,
        items:metersArr
      },
      callback() {
        message.success('新建出库单成功');
        that.setState({
          addModal: false,
        });
        const {
          outbound: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      id:'',
      type:'',
      status:'',
      page: 1,
      per_page: 30,
    });
  };

  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `outbound/edit`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('修改员工成功');
        that.setState({
          editModal: false,
        });
        const {
          outbound: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `outbound/remove`,
      payload: { id },
      callback: () => {
        message.success('删除出库单成功');
        const {
          outbound: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleConfirm= id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `outbound/confirm`,
      payload: { id },
      callback: () => {
        message.success('确认出库单成功');
        const {
          outbound: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  render() {
    const that = this;
    const {
      outbound: { data, loading, tableY, meta, searchParams, selectedRowKeys },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            outbound: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '出库单ID',
        width: 160,
        frozen: true,
        key: 'id',
        formatter: (event) => {
          if(event.row.isFirst){
            return <span title={event.value}>{event.value}</span>
          }else if(event.row.isCenter){
            return <img style={{marginLeft:'35px',position:'relative',top:'-3px'}} src={guawa2} alt=""/>
          }else{
            return <img style={{marginLeft:'35px',position:'relative',top:'-3px'}} src={guawa} alt=""/>
          }
        },
      },
      {
        name: '创建时间',
        width: 150,
        frozen: true,
        key: 'created_at',
        formatter: (event) => {
          if(event.row.isFirst){
            return <span title={event.value}>{event.value}</span>
          }else{
            return <div style={{width:'100%',height:'2px',background:'rgb(111 118 125)'}}></div>
          }
        },
      },
      {
        name: '材料名称',
        width: 120,
        frozen: true,
        key: 'material_name',
      },
      {
        name: '类型',
        width: 80,
        key: 'type',
        formatter: (event) => {
          //take：领料出库，lost：库存报损
          if(event.value==='take'){
            return  <Tag color="#9c27b0">领料出库</Tag>
          }else if(event.value==='lost'){
            return  <Tag color="#f50">库存报损</Tag>
          }else{
            return ''
          }
        },
      },
      {
        name: '状态',
        width: 80,
        key: 'status',
        formatter: (event) => {
          return <p className={event.value===1?'table-success table-status':'table-error table-status' }>{
            event.value===1?'已出库':'未出库'
          }</p>
        }
      },
      {
        name: '出库时间',
        width: 150,
        key: 'outbound_time',
      },

      {
        name: '所属仓库',
        width: 150,
        key: 'warehouse_name',
      },
      {
        name: '仓库区域',
        width: 120,
        key: 'warehouse_area_name',
      },
      {
        name: '出库数量',
        width: 100,
        key: 'count',
      },
      {
        name: '操作员',
        width: 100,
        key: 'operator_name',
      },
      {
        name: '备注',
        width: 100,
        key: 'remark',
      },
      {
        name: '操作',
        width: 180,
        key: 'right',
        classname: 'operate',
        formatter: (event) =>{
          if(event.row.isFirst){
            return <Fragment>
              {
                find(this.permissions, { name: 'outbound_operation' }) && event.row.status===-1&&
                <Fragment>
                  <Button
                    type="primary"
                    size="small"
                    icon="check"
                    onClick={(e) => {
                      confirm({
                        title: `确定要确认出库单 "${event.row.id}" 吗?`,
                        content: '数据不可逆，请谨慎操作！',
                        okText: '确定',
                        okType: 'danger',
                        cancelText: '取消',
                        centered:true,
                        maskClosable: true,
                        onOk() {
                          that.handleConfirm(event.row.id);
                        },
                        onCancel() {
                          console.log('Cancel');
                        },
                      });
                    }
                    }
                  >确认出库
                  </Button>
                  <Button
                    type="danger"
                    size="small"
                    icon="delete"
                    onClick={(e) => {
                      confirm({
                        title: `确定要删除出库单 "${event.row.id}" 吗?`,
                        content: '后数据不可逆，请谨慎操作！',
                        okText: '确定',
                        okType: 'danger',
                        cancelText: '取消',
                        centered:true,
                        maskClosable: true,
                        onOk() {
                          that.handleDelete(event.row.id);
                        },
                        onCancel() {
                          console.log('Cancel');
                        },
                      });
                    }
                    }
                  >删除
                  </Button>
                </Fragment>
              }
            </Fragment>
          }else{
            return  ''
          }
         },
      },

    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>出库统计</span>
      </div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                this.props.dispatch({
                  type: 'outbound/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination other={`  包含 ${data.length} 小项`} searchCondition={{ ...searchParams }} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal" title="新建出库单"/>}
        className="addModal"
        destroyOnClose
        visible={this.state.addModal}
        centered
        width={900}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ addModal: false });
        }}
        onOk={this.handleAdd}
      >
        <AddOrEditUser
          wrappedComponentRef={(inst) => this.AddForm = inst}/>

      </Modal>
    </div>;
  }
}

export default BasicList;
